package com.ruoyi.develop.goodsOrderIn.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson2.JSONArray;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.domain.entity.SysArea;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.constants.BusinessConstants;
import com.ruoyi.develop.goodsSale.domain.GoodsSale;
import com.ruoyi.develop.goodsSale.service.impl.GoodsSaleServiceImpl;
import com.ruoyi.develop.orderIronDetail.domain.OrderIronDetail;
import com.ruoyi.develop.orderIronRecord.domain.OrderIronRecord;
import com.ruoyi.system.mapper.SysAreaMapper;
import com.ruoyi.system.service.ISysAreaService;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.XLSReadStatus;
import org.jxls.reader.XLSReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.develop.goodsOrderIn.mapper.GoodsOrderInMapper;
import com.ruoyi.develop.goodsOrderIn.domain.GoodsOrderIn;
import com.ruoyi.develop.goodsOrderIn.service.IGoodsOrderInService;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 入库信息管理Service业务层处理
 *
 * @author qh
 * @date 2023-01-05
 */
@Service
public class GoodsOrderInServiceImpl implements IGoodsOrderInService {
    @Resource
    private GoodsOrderInMapper goodsOrderInMapper;
    @Resource
    private SysAreaMapper sysAreaMapper;
    @Resource
    private GoodsSaleServiceImpl goodsSaleService;
    @Autowired
    private ISysAreaService areaService;
    @Value(value = "${ruoyi.path}")
    public String basePath;
    @Value(value = "${ruoyi.templatePath}")
    public String templatePath;
    @Value(value = "${ruoyi.templateImport}")
    public String templateImport;


    /**
     * 查询入库信息管理
     *
     * @param id 入库信息管理主键
     * @return 入库信息管理
     */
    @Override
    public GoodsOrderIn selectById(String id) {
        return goodsOrderInMapper.selectById(id);
    }

    /**
     * 查询入库信息管理列表
     *
     * @param entity 入库信息管理
     * @return 入库信息管理
     */
    @Override
    public List<GoodsOrderIn> selectList(GoodsOrderIn entity) {
        return goodsOrderInMapper.selectList(entity);
    }

    /**
     * 查询入库信息管理列表 缓存
     *
     * @param entity 入库信息管理 缓存
     * @return 入库信息管理 缓存
     */
    @Override
    public List<GoodsOrderIn> selectListCache(GoodsOrderIn entity) {

        JSONArray arrayCache = SpringUtils.getBean(RedisCache.class).getCacheObject(CacheConstants.GOODS_ORDER_IN_KEY);
        if (StringUtils.isNotNull(arrayCache)) {
            return arrayCache.toList(GoodsOrderIn.class);
        }else{
            List<GoodsOrderIn> goodsOrderInList = goodsOrderInMapper.selectList(entity);
            SpringUtils.getBean(RedisCache.class).setCacheObject(CacheConstants.GOODS_ORDER_IN_KEY, goodsOrderInList);
            return  goodsOrderInList;
        }
    }

    @Override
    public List<GoodsOrderIn> listBatch(String[] ids) {
        return goodsOrderInMapper.listBatch(ids);
    }

    /**
     * 新增入库信息管理
     *
     * @param entity 入库信息管理
     * @return 结果
     */
    @Override
    public int insert(GoodsOrderIn entity) {
        if (StringUtils.isBlank(entity.getId())) {
            entity.setId(IdUtils.fastSimpleUUID());
        }
        // 新增默认
        entity.setDelFlag("3");
        entity.setAssessStatus(BusinessConstants.ASSESS_STATUS_UN);
        entity.setCreateBy(SecurityUtils.getUsername());
        entity.setCreateTime(DateUtils.getNowDate());
        return goodsOrderInMapper.insert(entity);
    }

    @Override
    public int insertOrderUpdateArea(GoodsOrderIn entity) {
        if (StringUtils.isBlank(entity.getId())) {
            entity.setId(IdUtils.fastSimpleUUID());
        }
        entity.setCreateBy(SecurityUtils.getUsername());
        entity.setCreateTime(DateUtils.getNowDate());
        if(StringUtils.isNotBlank(entity.getEmail())){
            entity.setBrand(entity.getEmail());
        }
        SysArea sysArea=areaService.selectAreaById(entity.getDeptId());
        if(sysArea!=null){
            if(entity.getCount()!=null && !entity.getCount().equals(BigDecimal.ZERO)){
                entity.setRemainderCount(entity.getCount());
                entity.setShengyu(entity.getRemainderCount().multiply(entity.getCostPrice()));
                sysArea.setCounts(sysArea.getCounts().add(entity.getCount()));
                sysArea.setShengyu(sysArea.getShengyu().add(entity.getCount()));
            }
            if(entity.getCostTax()!= null && !entity.getCostTax().equals(BigDecimal.ZERO)){
                sysArea.setTaxprice(sysArea.getTaxprice().add(entity.getCostTax()));
                sysArea.setAllmaoney(sysArea.getAllmaoney().add(entity.getCostTax()));
            }
            if(entity.getDun()!=null && !entity.getDun().equals(BigDecimal.ZERO)){
                sysArea.setAlldun(sysArea.getAlldun().add(entity.getDun()));
                sysArea.setShengdun(sysArea.getShengdun().add(entity.getDun()));
            }
            areaService.updateArea(sysArea);
        }
        return goodsOrderInMapper.insert(entity);
    }
    @Override
    public int insertIn(GoodsOrderIn entity) {
        SysArea sysArea=areaService.selectAreaById(entity.getDeptId());
        if (StringUtils.isBlank(entity.getId())) {
            entity.setId(IdUtils.fastSimpleUUID());
        }
        entity.setCreateBy(SecurityUtils.getUsername());
        entity.setCreateTime(DateUtils.getNowDate());
        entity.setDeptName(sysArea.getDeptName());
        goodsOrderInMapper.insert(entity);
        GoodsSale goodsSale=new GoodsSale();
        goodsSale.setGoodsId(entity.getId());
        goodsSale.setDeptId(entity.getDeptId());
        goodsSale.setDeptName(entity.getDeptName());
        goodsSale.setGoodsCode(entity.getCode());
        goodsSale.setGoodsName(entity.getName());
        goodsSale.setGoodModel(entity.getModel());
        goodsSale.setGoodsBrand(entity.getBrand());
        goodsSale.setUnit(entity.getUnit());
        goodsSale.setRemark(entity.getRemark());
        return goodsSaleService.insert(goodsSale);
    }
    /**
     * 修改入库信息管理
     *
     * @param entity 入库信息管理
     * @return 结果
     */
    @Override
    public int update(GoodsOrderIn entity) {
        entity.setUpdateBy(SecurityUtils.getUsername());
        entity.setUpdateTime(DateUtils.getNowDate());
        if (StringUtils.isNotBlank(entity.getImburseId())) {
            return 0;
        }
        List<GoodsOrderIn> goodsOrderInList = goodsOrderInMapper.selectList(new GoodsOrderIn());
        SpringUtils.getBean(RedisCache.class).setCacheObject(CacheConstants.GOODS_ORDER_IN_KEY, goodsOrderInList);
        return goodsOrderInMapper.update(entity);
    }

    @Override
    public int updateEntity(GoodsOrderIn entity) {
        entity.setUpdateBy(SecurityUtils.getUsername());
        entity.setUpdateTime(DateUtils.getNowDate());
        return goodsOrderInMapper.update(entity);
    }
    @Override
    public int editFee(GoodsOrderIn entity) {
        entity.setUpdateBy(SecurityUtils.getUsername());
        entity.setUpdateTime(DateUtils.getNowDate());
        return goodsOrderInMapper.update(entity);
    }

    /**
     * 产成品价格
     */
    public int updateGoodsBuyPrice(GoodsOrderIn entity) {
        entity.setMoney(entity.getShuidianFee().add(entity.getShebeiFee()).add(entity.getMojuFee()).add(entity.getFuliaoFee())
        .add(entity.getWeibaoFee()).add(entity.getFeiliaoFee()).add(entity.getYewuFee()).add(entity.getUserFee())
        .add(entity.getDoMoney()).add(entity.getMaterialMoney()));
        return goodsOrderInMapper.update(entity);
    }

    @Override
    public int updateIn(GoodsOrderIn entity) {
        SysArea sysArea=areaService.selectAreaById(entity.getDeptId());
        entity.setUpdateBy(SecurityUtils.getUsername());
        entity.setUpdateTime(DateUtils.getNowDate());
        entity.setDeptName(sysArea.getDeptName());
        if (StringUtils.isNotBlank(entity.getImburseId())) {
            return 0;
        }
        entity.setDeptName(sysArea.getDeptName());
        entity.setDeptId(sysArea.getDeptId());
        return goodsOrderInMapper.update(entity);
    }
    @Override
    public int updateForImburseId(GoodsOrderIn entity) {
        return goodsOrderInMapper.updateForImburseId(entity);
    }

    /**
     * 批量删除入库信息管理
     *
     * @param ids 需要删除的入库信息管理主键
     * @return 结果
     */
    @Override
    public int deleteByIds(String[] ids) {
        return goodsOrderInMapper.deleteByIds(ids);
    }

    /**
     * 删除入库信息管理信息
     *
     * @param id 入库信息管理主键
     * @return 结果
     */
    @Override
    public int deleteById(String id) {
        return goodsOrderInMapper.deleteById(id);
    }

    @Override
    public List<SysDictData> selectAllGoodsNames() {
        List<SysDictData> dictDatas = new ArrayList<>();
        List<GoodsOrderIn> lists = selectNamesList(new GoodsOrderIn());
        lists.stream().forEach(entity -> {
            if (entity != null && StringUtils.isNotBlank(entity.getName())) {
                SysDictData dict = new SysDictData();
                dict.setDictLabel(entity.getName());
                dict.setDictValue(entity.getName());
                dictDatas.add(dict);
            }
        });
        return dictDatas;
    }

    private List<GoodsOrderIn> selectNamesList(GoodsOrderIn goodsOrderIn) {
        return goodsOrderInMapper.selectNamesList(goodsOrderIn);
    }

    @Override
    public List<SysDictData> selectAllGoodsBrands() {
        List<SysDictData> dictDatas = new ArrayList<>();
        List<GoodsOrderIn> lists = selectBrandsList(new GoodsOrderIn());
        lists.stream().forEach(entity -> {
            SysDictData dict = new SysDictData();
            if (entity != null && StringUtils.isNotBlank(entity.getBrand())) {
                dict.setDictLabel(entity.getBrand());
                dict.setDictValue(entity.getBrand());
                dictDatas.add(dict);
            }
        });
        return dictDatas;
    }

    private List<GoodsOrderIn> selectBrandsList(GoodsOrderIn goodsOrderIn) {
        return goodsOrderInMapper.selectBrandsList(goodsOrderIn);
    }

    @Override
    public void updateReimburseStatusByImburseId(GoodsOrderIn orderInParam) {
        goodsOrderInMapper.updateReimburseStatusByImburseId(orderInParam);
    }

    @Override
    public Map<String, Object> importData(GoodsOrderIn entity, MultipartFile file) {
        String tmplName = "goodsOrderIn.xml";
        String errortext = "";
        Map<String, Object> map = new HashMap<>();
        int i = 0;
        int j = 0;
        List<GoodsOrderIn> list = new ArrayList<>();
        List<SysArea>  sysAreaList = sysAreaMapper.selectAreaList(new SysArea());
        try {
            InputStream in = new FileInputStream(basePath + File.separator
                    + templatePath + File.separator + templateImport + File.separator + tmplName);
            XLSReader mainReader = ReaderBuilder.buildFromXML(in);
            Map beans = new HashMap();
            beans.put("list", list);
            XLSReadStatus readStatus = mainReader.read(file.getInputStream(), beans);
            if (readStatus.isStatusOK()) {
                for (GoodsOrderIn goodsOrderIn : list) {
                    sysAreaList.stream().filter(sysArea -> sysArea.getCode().equals(goodsOrderIn.getDeptId())).findFirst().ifPresent(sysArea -> goodsOrderIn.setDeptId(sysArea.getDeptId()));
                    sysAreaList.stream().filter(sysArea -> sysArea.getCode().equals(goodsOrderIn.getDeptId())).findFirst().ifPresent(sysArea -> goodsOrderIn.setDeptName(sysArea.getDeptName()));
                    this.insert(goodsOrderIn);
                    i++;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("errorText", errortext);
        map.put("num", i);
        map.put("numupdate", j);
        return map;
    }

    @Override
    public String getMaxCodeGoodsCodeByArea(GoodsOrderIn entity) {
        return goodsOrderInMapper.getMaxCodeGoodsCodeByArea(entity);
    }

    @Override
    public List<GoodsOrderIn> selectAssessList(GoodsOrderIn entity) {
        return goodsOrderInMapper.selectAssessList(entity);
    }

    @Override
    public GoodsOrderIn selectByCode(String code) {
        return goodsOrderInMapper.selectByCode(code);
    }

    @Override
    public String getMaxCode() {
        return goodsOrderInMapper.getMaxCode();
    }

    @Override
    public GoodsOrderIn selectByCodeAll(String code) {
        return goodsOrderInMapper.selectByCodeAll(code);
    }

    @Override
    public String getGoodsCodeByArea(GoodsOrderIn entity) {

        SysArea area = areaService.selectAreaById(entity.getDeptId());
        String code = area.getCode();
        GoodsOrderIn goodsOrderIn = new GoodsOrderIn();
        goodsOrderIn.setCode(area.getCode());
        String codeMax = goodsOrderInMapper.getMaxCodeGoodsCodeByArea(goodsOrderIn);
        // 如果存在 则加1 否则返回0001
        if (StringUtils.isNotBlank(codeMax)) {
            codeMax = String.format("%0"+codeMax.length()+"d",Long.parseLong(codeMax));
        }
        else {
            codeMax = area.getCode()+"0001";
        }
        do {
            String codeMaxTemp = "";
            codeMaxTemp = String.format("%0"+codeMax.length()+"d",Long.parseLong(codeMax)+1);
            // 如果加法超过了该类别下的所有编码，则多一位补0
            if(!codeMaxTemp.contains(code)){
                int start = code.length(); // 从第2位开始（注意：这里的索引是从0开始的）
                int end = codeMax.length()-1; // 到第5位结束（包含第5位）
                StringBuilder sb = new StringBuilder(codeMax);
                for (int i = start; i <= end; i++) {
                    sb.setCharAt(i, '0');
                }
                codeMax = sb+"0";
            }else{
                codeMax = codeMaxTemp;
            }
        }
        while (goodsOrderInMapper.selectByCodeAll(codeMax) != null);
        return codeMax;
    }


}
